<template>
    <div class="wrap">
        <div @click="handClick">
            <slot></slot>
        </div>
        <a-modal title="" :visible="visible" @ok="handleOk" @cancel="handleCancel" :closable="false" :centered="true"
            :confirm-loading="confirmLoading || loading" width="calc(70vw+40px)" okText="保存" :maskClosable="false">
            <a-spin :spinning="loading" style="width: 100%;height: 100%;">
                <div class="modalWrap">
                    <div ref="tui-image-editoRef" class="tui-image-editor"></div>
                </div>
            </a-spin>
        </a-modal>
    </div>
</template>
<script>
import 'tui-image-editor/dist/tui-image-editor.css'
import 'tui-color-picker/dist/tui-color-picker.css'
import ImageEditor from 'tui-image-editor'
import { customTheme, locale_zh } from './js/js'
export default {
    name: 'PictureEdit',
    props: {
        item: {
            type: [Object, String],
        },
        onCallBack:{
            type:Function,
        }
    },
    data() {
        return {
            instance: null, // 创建的画布对象
            visible: false,
            confirmLoading: false,
            loading: false,
            base64Url: '',
            showValueUrl: '',
        }
    },
    mounted() {
        // 页面创建完成后调用
    },
    methods: {
        openPage(url) {
            // this.editImg = true
            this.$nextTick(() => {
                this.init(url)
            })
        },
        init(url) {
            this.instance = new ImageEditor(this.$refs['tui-image-editoRef'], {
                includeUI: {
                    loadImage: {
                        path: url,
                        name: 'image',
                    },
                    // menu: ['resize', 'crop', 'rotate', 'draw', 'shape', 'icon', 'text', 'filter'], // 底部菜单按钮列表 隐藏镜像flip和遮罩mask
                    menu: ['draw', 'shape', 'icon', 'text'], // 底部菜单按钮列表 隐藏镜像flip和遮罩mask
                    initMenu: 'shape', // 默认打开的菜单项
                    menuBarPosition: 'left', // 菜单所在的位置
                    locale: locale_zh, // 本地化语言为中文
                    theme: customTheme, // 自定义样式
                },
                cssMaxWidth: 1000, // canvas 最大宽度
                cssMaxHeight: 600, // canvas 最大高度
            })
            document.getElementsByClassName('tui-image-editor-main')[0].style.top = '45px' // 调整图片显示位置
            document.getElementsByClassName('tie-btn-reset tui-image-editor-item help')[0].style.display = 'none' // 隐藏顶部重置按钮
            document.getElementsByClassName('tie-text-align-button')[0].style.display = 'none' // 隐藏文字对齐选项
        },
        // 保存图片，并上传
        save() {
            const base64String = this.instance.toDataURL() // base64 文件
            const urlData = window.atob(base64String.split(',')[1])
            const ia = new Uint8Array(urlData.length)
            for (let i = 0; i < urlData.length; i++) {
                ia[i] = urlData.charCodeAt(i)
            }
            const blob = new Blob([ia], { type: 'image/png' }) // blob 文件
            const data = new FormData()
            data.append('file', blob)
            data.append('id', this.item.id)
            data.append('imageUrl', this.item.url)
            this.confirmLoading = true;
            this.postAxios(this.$imageEdit, data).then((res) => {
                if (res.code == 200) {
                    this.$message.success({
                        content: res.msg || res.data,
                        duration: 2.5,
                    });
                    this.visible = false;
                    this.onCallBack();
                }
            }).catch(() => {
            }).finally(() => {
                this.confirmLoading = false;
            })
            // upload file
        },
        handleOk() {
            this.save();
        },
        handleCancel() {
            this.visible = false;
        },
        addBackgroundColorToBase64Image(base64ImageData, backgroundColor) {
            const img = new Image();
            img.src = base64ImageData;
            return new Promise((resolve, reject) => {
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.fillStyle = backgroundColor;
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    const newBase64Image = canvas.toDataURL();
                    resolve(newBase64Image);
                };
                img.onerror = (error) => {
                    reject(error);
                };
            });
        },
        getImgBase() {
            if (this.item.url) {
                this.loading = true;
                this.getAxios(this.$addWhiteBackground, { url: this.item.url }).then((res) => {
                    if (res.code == 200) {
                        this.addBackgroundColorToBase64Image(`data:image/png;base64,${res.data}`, 'white')
                            .then((newBase64Image) => {
                                // newBase64Image 是添加了背景颜色后的新图片的 Base64 编码
                                this.showValueUrl = newBase64Image

                                this.openPage(newBase64Image)
                            })
                            .catch((error) => {
                            });
                    }
                }).catch(() => {
                }).finally(() => {
                    this.loading = false;
                })
            }
        },
        handClick() {
            this.visible = true;
            this.getImgBase();
            // 测试代码
            // let url = 'https://static.dingtalk.com/media/lQDPM4viLRJLVz3NA8jNBQywG6vGYCUP2GMHEo1kq5pXAA_1292_968.jpg';
            // // let url = 'https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c1d7a1feb60346449c1a64893888989a~tplv-k3u1fbpfcp-watermark.image';
            // this.openPage(url)
        }
    },
}
</script>
<style lang="less" scoped>
.wrap {
    height: 100%;
    width: 100%;
}

.modalWrap {
    width: calc(70vw + 40px);
    height: 80vh;
}

::v-deep {
    .ant-modal-body {
        padding: 0px;
    }
}
</style>